package club.mzywucai.blog.file_system.service.impl;

import club.mzywucai.blog.file_system.mapper.FileInformationMapper;
import club.mzywucai.blog.file_system.pojo.domain.JsonData;
import club.mzywucai.blog.file_system.pojo.domain.PageBean;
import club.mzywucai.blog.file_system.pojo.po.FileCategoryTreePo;
import club.mzywucai.blog.file_system.pojo.po.FileRatioPo;
import club.mzywucai.blog.file_system.pojo.vo.*;
import club.mzywucai.blog.file_system.service.FileInformationService;
import club.mzywucai.blog.file_system.util.DateToMsgUtil;
import club.mzywucai.blog.file_system.util.XORUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author mzywucai
 * @Description
 * @date 2019/2/11
 */
@Service
@PropertySource({"classpath:config/application.properties"})
public class FileInformationServiceImpl implements FileInformationService {
    @Value("${file.uri.secret}")
    String secret;
    @Value("${file.page.size}")
    Integer pageSize;

    @Autowired
    FileInformationMapper fileInformationMapper;

    @Override
    public JsonData getRecentIUploadFileVoList() {
        List<RecentIUploadFileVo> recentIUploadFileVoList =
                fileInformationMapper.getRecentIUploadFileVoList();

        // 进行转置
        for (RecentIUploadFileVo vo : recentIUploadFileVoList) {
            String msg = DateToMsgUtil.msg(vo.getFileUploadDate());
            vo.setFileUploadDateMsg(msg);
        }



        return JsonData.buildSuccess(0, recentIUploadFileVoList, "操作成功");
    }

    @Override
    public JsonData getFileDetailVoByFileInfoId(long fileInfoId) {
        FileDetailVo fileDetailVoByFileInfoId =
                fileInformationMapper.getFileDetailVoByFileInfoId(fileInfoId);
        if (null == fileDetailVoByFileInfoId) {
            return JsonData.buildError("文件不存在");
        }

        String fileURI = fileDetailVoByFileInfoId.getFileURI();

        String encodeFileURI = XORUtil.encode(fileURI, secret);

        fileDetailVoByFileInfoId.setFileURI(encodeFileURI);

        return JsonData.buildSuccess(0, fileDetailVoByFileInfoId, "操作成功");

    }

    @Override
    public JsonData getFileRatioAllInSystem() {
        // 获取所有的
        return getFileRatioVos(null);
    }

    @Override
    public JsonData getFileRatioAboutUser(HttpSession session) {
        Long userId = getUserId(session);

        if (null == userId) {
            return JsonData.buildError("请先登录");
        }

        return getFileRatioVos(userId);

    }

    @Override
    public JsonData getFileBasicListAllInSystem(FileBasicListQueryTermsVo fileBasicListQueryTermsVo) {
        List<Long> fileCategoryList = fileBasicListQueryTermsVo.getFileCategoryList();
        Integer orderBy = fileBasicListQueryTermsVo.getOrderBy();
        Integer pageNum = fileBasicListQueryTermsVo.getPageNum();
        String condition = fileBasicListQueryTermsVo.getCondition();

        JsonData pageBeanJsonData = getPageBeanJsonData(null, fileCategoryList, orderBy, pageNum, condition);

        return pageBeanJsonData;
    }

    @Override
    public JsonData getFileBasicListAboutUser(FileBasicListQueryTermsVo fileBasicListQueryTermsVo, HttpSession session) {
        Long userId = getUserId(session);

        if (null == userId) {
            return JsonData.buildError("请先登录");
        }
        List<Long> fileCategoryList = fileBasicListQueryTermsVo.getFileCategoryList();
        Integer orderBy = fileBasicListQueryTermsVo.getOrderBy();
        Integer pageNum = fileBasicListQueryTermsVo.getPageNum();
        String condition = fileBasicListQueryTermsVo.getCondition();
        
        JsonData pageBeanJsonData = getPageBeanJsonData(userId, fileCategoryList, orderBy, pageNum, condition);

        return pageBeanJsonData;
    }

    @Override
    /*public JsonData delFile(long fileInfoId, HttpSession session) {*/
    public JsonData delFile(Long fileInfoId, HttpSession session) {
        Long userId = getUserId(session);
        UserVo user = (UserVo) session.getAttribute("user");

        if (null == user) {
            return JsonData.buildError("请先登录");
        }

        List<Long> ownFileList = fileInformationMapper.getOwnFileList(userId);
        // 测试
        System.out.println(ownFileList);
        System.out.println(ownFileList.contains(fileInfoId));

        if (!ownFileList.contains(fileInfoId)) {
            return JsonData.buildError("您无权删除此文件");
        }

        fileInformationMapper.delFile(fileInfoId);

        return JsonData.buildSuccess(0, "ok", "删除成功");
    }

    @Override
    public JsonData getFileCategoryTree() {
        List<FileCategoryTreePo> fileCategoryTree = fileInformationMapper.getFileCategoryTree();
        // Map<FileCategoryTreeParentNodeVo, List<FileCategoryTreeChildNodeVo>> map = new TreeMap<>();
        Map<Long, FileCategoryTreeParentNodeVo> map = new TreeMap<>();

        FileCategoryTreeParentNodeVo fileCategoryTreeParentNodeVo;
        for (FileCategoryTreePo po : fileCategoryTree) {
            // new
            fileCategoryTreeParentNodeVo = new FileCategoryTreeParentNodeVo();
            // set值
            fileCategoryTreeParentNodeVo.setParentId(po.getParentId());
            fileCategoryTreeParentNodeVo.setParentName(po.getParentName());
            fileCategoryTreeParentNodeVo.setParentRemark(po.getParentRemark());
            // set childNode容器ArrayList
            fileCategoryTreeParentNodeVo.setChild(new ArrayList<>());
            // put in map
            map.put(po.getParentId(), fileCategoryTreeParentNodeVo);
        }

        FileCategoryTreeChildNodeVo fileCategoryTreeChildNodeVo;
        for (FileCategoryTreePo po : fileCategoryTree) {
            // 取parentNode
            FileCategoryTreeParentNodeVo parentNode = map.get(po.getParentId());
            // 创建childNode
            fileCategoryTreeChildNodeVo = new FileCategoryTreeChildNodeVo();
            fileCategoryTreeChildNodeVo.setChildId(po.getChildId());
            fileCategoryTreeChildNodeVo.setChildName(po.getChildName());
            // 拿到child容器
            List<FileCategoryTreeChildNodeVo> child = parentNode.getChild();
            // 将childNode添仅对应的parentNode中
            child.add(fileCategoryTreeChildNodeVo);
        }

        // 将Map转回List
        Set<Map.Entry<Long, FileCategoryTreeParentNodeVo>> entries = map.entrySet();
        List<FileCategoryTreeParentNodeVo> fileCategoryTreeVo = new ArrayList<>();
        for (Map.Entry<Long, FileCategoryTreeParentNodeVo> entry : entries) {
            fileCategoryTreeVo.add(entry.getValue());
        }

        return JsonData.buildSuccess(0, fileCategoryTreeVo, "ok");
    }

    private JsonData getPageBeanJsonData(Long userId, List<Long> fileCategoryList, int orderBy, int pageNum, String condition) {
        // 拿到count
        int count = fileInformationMapper.getFileBasicCount(userId, fileCategoryList, condition);
        PageBean<FileBasicVo> pageBean = new PageBean<>(pageNum, count, pageSize);

        // 计算出开始页：(当前页 - 1) * 页容
        int pageBegin = pageBean.getPageBeginIndex();

        // 获取当前页的数据，并放入到pageBean中
        List<FileBasicVo> fileBasic =
                fileInformationMapper.getFileBasic(userId, fileCategoryList, orderBy, pageBegin, pageSize, condition);

        pageBean.setContent(fileBasic);

        // 返回
        return JsonData.buildSuccess(0, pageBean, "ok");
    }

    private JsonData getFileRatioVos(Long userId) {
        List<FileRatioPo> fileRatioPos = fileInformationMapper.getFileRatio(userId);

        List<FileRatioVo> fileRatioVos = new ArrayList<>();

        int count = 0;
        for (FileRatioPo po : fileRatioPos) {
            count += po.getNumber();
        }

        FileRatioVo fileRatioVo;
        for (FileRatioPo po : fileRatioPos) {
            fileRatioVo = new FileRatioVo();

            fileRatioVo.setFileCategoryLevel1(po.getFileCategoryLevel1());
            fileRatioVo.setRemark(po.getRemark());

            double percentsNumberTMP = po.getNumber() * 1.0 / count;

            // 先 * 10000 向下取整，再 / 100
            percentsNumberTMP = percentsNumberTMP * 10000;

            percentsNumberTMP = Math.floor(percentsNumberTMP);

            percentsNumberTMP = percentsNumberTMP / 100;

            // 格式化两个小数点：这样是四舍五入，不行；
            // String percentsString = String.format("%.2f", percentsNumber);

            String percentsString = String.valueOf(percentsNumberTMP);

            fileRatioVo.setPercents(percentsString);

            fileRatioVos.add(fileRatioVo);
        }


        return JsonData.buildSuccess(0, fileRatioVos, "ok");
    }

    private Long getUserId(HttpSession session) {
        UserVo user = (UserVo) session.getAttribute("user");

        if (null == user) {
            return null;
        }

        Long userId = user.getUserId();

        return userId;
    }
}
